package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDataVo;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Map;

/**
 * 设备信息Service业务层处理
 * 
 * @author fhy
 * @date 2025-10-17
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper,Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    @Override
    public void syncProductList() {
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = client.listProducts(request);
        if(response.getHttpStatusCode()!=200){
            throw new BaseException("产品同步失败");
        }
        List<ProductSummary> products = response.getProducts();
        redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).set(JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        String string = redisTemplate.boundValueOps(CacheConstants.IOT_ALL_PRODUCT_LIST).get();
        return JSONUtil.toList(string, ProductVo.class);
    }

    @Override
    public void registerDevice(DeviceDto dto) {
        //注册设备前
        //查询设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Device::getDeviceName,dto.getDeviceName());
        if (this.count(queryWrapper) > 0){
            throw new BaseException("设备名称重复");
        }
        //查询设备标识是否重复
        queryWrapper.eq(Device::getNodeId,dto.getNodeId());
        if (this.count(queryWrapper) > 0){
            throw new BaseException("设备标识码重复");
        }
        //查询同一位置是否绑定了相同的产品
        queryWrapper.eq(Device::getLocationType,dto.getLocationType());
        queryWrapper.eq(Device::getBindingLocation,dto.getBindingLocation());
        queryWrapper.eq(Device::getProductKey,dto.getProductKey());
        if (this.count(queryWrapper) > 0 ){
            throw new BaseException("同一位置上绑定了相同的产品");
        }
        //调用华为云iot远程注册设备
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setNodeId(dto.getNodeId());
        body.setDeviceName(dto.getDeviceName());
        body.setProductId(dto.getProductKey());
        //秘钥
        AuthInfo authInfo = new AuthInfo();

        String secret = RandomUtil.randomString(32);
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);
        body.setDescription(dto.getDeviceDescription());
        addDeviceRequest.setBody(body);
        AddDeviceResponse response = client.addDevice(addDeviceRequest);
        if (response.getHttpStatusCode()!=201) {
            throw new BaseException("IOT设备添加失败");
        }
        String deviceId = response.getDeviceId();
        // 本地存储设备
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setIotId(deviceId);
        device.setSecret(secret);

        this.save(device);


    }

    @Override
    public DeviceDetailVo deviceDetail(String iotId) {
        //华为云iot设备查询
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode()!=200){
            throw new BaseException("iot设备查询失败");
        }
        //本地查询
        Device device =  this.getOne(new LambdaQueryWrapper<Device>().eq(Device::getIotId,iotId));
        if (device==null){
            throw new BaseException("设备不存在");
        }
        DeviceDetailVo detailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        detailVo.setDeviceStatus(response.getStatus());
        String activeTime = response.getActiveTime();
        LocalDateTime parse = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
        LocalDateTime dateTime = DateTimeZoneConverter.utcToShanghai(parse);
        detailVo.setActiveTime(dateTime);


        return detailVo;
    }

    @Override
    public List<DeviceDataVo> queryServiceProperties(String iotId) {
        List<DeviceDataVo> list = new ArrayList<>();
        //华为云iot设备查询
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode()!=200){
            throw new BaseException("iot设备查询失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if(CollUtil.isNotEmpty(shadow)){
            DeviceShadowData deviceShadowData = shadow.get(0);
            DeviceShadowProperties reported = deviceShadowData.getReported();
            String eventTime = reported.getEventTime();
            LocalDateTime dateTime = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime utc = DateTimeZoneConverter.utcToShanghai(dateTime);
            Object properties = reported.getProperties();
            JSONObject jsonObject = JSONUtil.parseObj(properties);
            for (Map.Entry<String, Object> stringObjectEntry : jsonObject) {
                DeviceDataVo deviceDataVo = new DeviceDataVo();
                deviceDataVo.setFunctionId(stringObjectEntry.getKey());
                deviceDataVo.setEventTime(utc);
                deviceDataVo.setValue(stringObjectEntry.getValue());
                list.add(deviceDataVo);
            }
        }
        return list;
    }
    //删除设备
    @Override
    public void deleteDevice(String iotId) {
        //删除华为云iot设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        client.deleteDevice(request);
        //删除本地设备
        deviceMapper.ByIOTId(iotId);
    }

    @Override
    public void updateDevice(DeviceDto dto) {
        //判断设备名称是否重复
        LambdaQueryWrapper<Device> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Device::getDeviceName,dto.getDeviceName());
        queryWrapper1.ne(dto.getId() != null, Device::getId, dto.getId());
        Device one = this.getOne(queryWrapper1);
        if(one!=null){

            throw new BaseException("设备名称不能重复");
        }
        //判断同一位置是否有同一设备
        LambdaQueryWrapper<Device> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.eq(Device::getRemark,dto.getRemark());
        queryWrapper3.eq(Device::getProductKey,dto.getProductKey());
        queryWrapper3.ne(dto.getId() != null, Device::getId, dto.getId());
        Device three = this.getOne(queryWrapper3);
        if(three!=null){
            throw new BaseException("同一位置不可以有同一设备");
        }
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(dto.getIotId());
        UpdateDevice body = new UpdateDevice();
        AuthInfoWithoutSecret authInfobody = new AuthInfoWithoutSecret();
        authInfobody.withSecureAccess(true);
        //将认证信息对象 设置到 请求主体 中
        body.withAuthInfo(authInfobody);
        //iot平台更新自带字段
        body.withDescription(dto.getDeviceDescription());
        body.withDeviceName(dto.getDeviceName());
        //某个对象设置扩展信息
        // 设置设备扩展信息
        Map<String, Object> extension = new HashMap<>();
        extension.put("physicalLocationType", dto.getPhysicalLocationType());
        extension.put("locationType", dto.getLocationType());
        extension.put("bindingLocation", dto.getBindingLocation());
        extension.put("remark", dto.getRemark());
        extension.put("nodeId", dto.getNodeId());
        extension.put("productKey", dto.getProductKey());
        extension.put("productName", dto.getProductName());
        String escapedJson2 =JSONUtil.toJsonStr(extension).replace("\"", "\\\"");
        body.withExtensionInfo(escapedJson2);
        //是将请求体对象设置到主请求对象中
        request.withBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        if(response.getHttpStatusCode()!=200){
            throw new BaseException("IOT修改设备失败");
        }
        LambdaUpdateWrapper<Device> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Device::getId,dto.getId());
        updateWrapper.set(Device::getDeviceName,dto.getDeviceName());
        updateWrapper.set(Device::getRemark,dto.getRemark());
        this.update(updateWrapper);
    }


}
